import {
  ds
} from "../../../../tools/data"
import {
  pages
} from '../../../../tools/pages'
import {
  ui
} from '../../../../tools/ui'

Page({
  data: {
    action: 'select',
    errMsg: "",
  },
  async init() {
    ui.loading()
    ds.coll('coupons')
      .limit(50)
      .get()
      .then(res => {
        this.setData({
          list: res.data
        })
        ui.loading(false)
      })
  },
  addCoupon(e) {
    wx.navigateTo({
      url: '../edit/couponEdit',
    })
  },
  longpressGoodsTap(e) {
    const list = this.data.list,
      that = this
    const id = e.target.dataset.id
    ui.confirmx('是否删除？')
      .then(res => {
        if (!res) return
        ui.loading()
        ds.cloudRemove('coupons', {
          _id: id
        }, res => {
          // console.log(res)
          const success = res.result.errMsg.endsWith(":ok")
          ui.loading(false)
          if (!success) ui.toast(false, res)
          else ui.toast(success, '', res => {
            that.setData({
              list: list.filter(ele => ele._id != id)
            })
          })
        })
      })
  },
  couponClick(e) {
    if (this.data.action == 'edit') {
      wx.navigateTo({
        url: '../edit/couponEdit?action=edit&id=' + e.target.dataset.id,
      })
    } else {
      pages.back(prePage => {
        prePage.couponSelected(e.target.dataset)
      })
    }

  },

  onShow() {

  },

  onLoad(option) {
    this.setData({
      action: option.action
    })
    this.init();
  },
});